import React, { Component, createRef } from 'react'
import styles from './index.module.scss'

// 导入图片资源
import loginIconImg from '../../assets/img/login_icon.png'
import loginBgImg from '../../assets/img/login_bg.png'

// 导入antd相关组件
import { Form, Input, Button, Checkbox, Row, Col, message } from 'antd'
import { UserOutlined, LockOutlined, KeyOutlined } from '@ant-design/icons'

import { saveToken } from '../../utils/token'

// 导入子组件
import Register from './register'

export default class Index extends Component {
  constructor () {
    super()

    this.state = {
      loginCaptcha: process.env.REACT_APP_BASEURL + '/captcha?type=login'
    }

    this.registerRef = createRef()
  }

  // 登录
  onFinish = async values => {
    const res = await this.$axios.post('/login', values)

    if (res.code === 200) {
      // 提示
      message.success('登录成功~')

      // 保存token
      saveToken(res.data.token)

      // 路由跳转
      this.props.history.push('/layout')
    } else {
      // 提示
      message.error(res.message)
      // 刷新验证码
      this.changeLoginCaptcha()
    }
  }

  changeLoginCaptcha = () => {
    this.setState({
      loginCaptcha:
        process.env.REACT_APP_BASEURL +
        `/captcha?type=login&t=${new Date() - 0}`
    })
  }

  // 注册
  register = () => {
    this.registerRef.current.setVisible(true)
  }

  render () {
    return (
      <div className={styles.loginContainer}>
        <div className={styles.left}>
          <div className={styles['title-box']}>
            <img src={loginIconImg} alt='' />
            <span className={styles.title}>黑马面面</span>
            <span className={styles.line}></span>
            <span className={styles['sub-title']}>用户登录</span>
          </div>
          <Form
            className={styles['login-form']}
            initialValues={{
              phone: '18511111111',
              password: '12345678',
              agreement: true
            }}
            onFinish={this.onFinish}
            size='large'
          >
            <Form.Item
              name='phone'
              rules={[
                {
                  validator: (_, value) => {
                    if (!value) return Promise.reject('手机号不能为空')

                    const reg = /^1[3456789][0-9]{9}$/
                    if (!reg.test(value)) return Promise.reject('手机号不合法')

                    return Promise.resolve()
                  }
                }
              ]}
              validateTrigger='onBlur'
            >
              <Input
                prefix={<UserOutlined className='site-form-item-icon' />}
                placeholder='请输入手机号'
              />
            </Form.Item>
            <Form.Item
              name='password'
              rules={[
                { required: true, message: '密码不能为空!' },
                { max: 16, min: 6, message: '密码长度必须是6-16位之间!' }
              ]}
              validateTrigger='onBlur'
            >
              <Input
                prefix={<LockOutlined className='site-form-item-icon' />}
                type='password'
                placeholder='请输入密码'
              />
            </Form.Item>
            <Row>
              <Col span={16}>
                <Form.Item
                  name='code'
                  rules={[{ required: true, message: '验证码不能为空!' }]}
                  validateTrigger='onBlur'
                >
                  <Input
                    prefix={<KeyOutlined className='site-form-item-icon' />}
                    type='text'
                    placeholder='请输入验证码'
                  />
                </Form.Item>
              </Col>
              <Col span={7} style={{ marginLeft: '10px' }}>
                <img
                  onClick={this.changeLoginCaptcha}
                  style={{ width: '100%', height: '40px' }}
                  src={this.state.loginCaptcha}
                  alt=''
                />
              </Col>
            </Row>
            <Form.Item
              name='agreement'
              rules={[
                {
                  validator: (_, value) =>
                    value
                      ? Promise.resolve()
                      : Promise.reject('必须勾选用户协议!')
                }
              ]}
              valuePropName='checked'
            >
              <Checkbox>
                我已经阅读并同意
                <a className='login-form-forgot' href='http://www.baidu.com'>
                  用户协议
                </a>
                和
                <a className='login-form-forgot' href='http://www.jd.com'>
                  隐私条款
                </a>
              </Checkbox>
            </Form.Item>
            <Form.Item>
              <Button type='primary' htmlType='submit' block>
                登录
              </Button>
            </Form.Item>
            <Form.Item>
              <Button type='primary' block onClick={this.register}>
                注册
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div>
          <img src={loginBgImg} alt='' />
        </div>
        <Register ref={this.registerRef} />
      </div>
    )
  }
}
